import { defineStore } from 'pinia';
import { ref, computed,reactive } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios'; // 假设已安装axios
// 设置axios的基础URL
axios.defaults.baseURL = 'https://www.you04.cn';
//获取token
const token = ref(sessionStorage.getItem('token') || localStorage.getItem('token'));
export const useRoleStore = defineStore('role', () => {
  // 状态
  const roles = ref([]);
  const rolesList=ref([])
  const loading = ref(false);
  const error = ref(null);
  const pagination =ref(
    {
      page:1,
      pageSize:10,
      total:0
    }
  )
  const searchForm=reactive({
    name:''
  })
  // 获取角色列表，可带分页和搜索关键字
  const getRoles = async ({ page = pagination.value.page, pageSize = pagination.value.pageSize, keyword, isActive } = {}) => {
    try {
      console.log('getRoles 请求参数:', { page, pageSize, keyword, isActive });
      
      const response = await axios.get('/api/roles', {
        headers: { 'Authorization': `Bearer ${token.value}` },
        params: {
          page,
          size: pageSize,
          keyword,
          isActive
        }
      });
      
      console.log('getRoles 响应数据:', response.data);
      
      const { items, totalCount, pageIndex, pageSize: ps } = response.data.data;
      // 字段映射，确保表格字段名一致
      roles.value = Array.isArray(items)
        ? items.map(item => ({
            id: item.id,
            name: item.name,
            description: item.description,
            isActive: item.isActive ?? item.active,
            createdAt: item.createdAt ?? item.created_at,
            // 其他字段按需补充
          }))
        : [];
      pagination.value = { page: pageIndex, pageSize: ps, total: totalCount };
      return { roles: roles.value, pagination: pagination.value };
    } catch (error) {
      console.error('getRoles 错误:', error);
      throw new Error(error.response?.data?.message || 'fetch_roles_failed');
    }
  }

//添加角色接口方法
  const addRole =async(role)=>{
        try {
      const response = await axios.post('/api/roles', role, {
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      return response.data; // 后端返回添加的用户信息
    } catch (error) {
      throw new Error(error.response?.data?.message || '添加角色失败');
    }
  }
  const deleteRole =async(roleId)=>{
try {
      await axios.delete(`/api/roles/${roleId}`, {
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
    } catch (error) {
      throw new Error(error.response?.data?.message || 'delete_user_failed');
    }
  }
  //编辑角色接口方法
  const editRole =async(roleId,role)=>{
        try {
      const response = await axios.put(`/api/roles/${roleId}`, role, {
        headers: { 'Authorization': `Bearer ${token.value}` }
      });
      return response.data; 
    } catch (error) {
      throw new Error(error.response?.data?.message || '修改角色失败');
    }
  }
  //角色搜索查询实现
  const fetchRoles= async (searchParams, paginationParams = {}) => {
    try {
        const params = {
        page: paginationParams.page || pagination.value.page,
        size: paginationParams.pageSize || pagination.value.pageSize
      };

      if (searchParams.name) params.name = searchParams.name;
      const response = await axios.get('/api/roles/search', {
        headers: { 'Authorization': `Bearer ${token.value}` },
        params
      })

      const { items, totalCount, pageIndex, pageSize } = response.data.data;
      roles.value = items;
      pagination.value = {
        page: pageIndex,
        pageSize: pageSize,
        total: totalCount
      };
      return { roles: roles.value, pagination: pagination.value }
    } catch (error) {
      console.error('搜索角色错误:', error);
      throw new Error(error.response?.data?.message || 'search_roles_failed');
    }
  }
  //单个角色
  const getsingle =async(roleId)=>{
try {
     const res= await axios.get(`/api/roles/${roleId}`, {
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      return res.data.data
    } catch (error) {
      throw new Error(error.response?.data?.message || 'get_user_failed');
    }
  }
  return {
    roles,
    loading,
    error,
    fetchRoles,
    getRoles,
    deleteRole,
    addRole,
    editRole,
    getsingle
  };
})